<!-- 文件管理 -->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入文件名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <el-button
          v-hasPerm="['sys:file:manage:create']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="预览" prop="path" width="85" align="center">
          <template #default="scope">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.path"
              :preview-src-list="previewList"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column label="文件名称" prop="name" min-width="100" />
        <el-table-column
          label="文件大小"
          prop="size"
          width="100"
          align="center"
          :formatter="formatterSize"
        />
        <el-table-column label="类型" prop="suffix" width="80" align="center" />
        <el-table-column label="MD5" prop="md5" show-overflow-tooltip />
        <el-table-column
          label="上传平台"
          prop="platform"
          width="90"
          align="center"
        />
        <el-table-column
          label="上传者id"
          prop="userId"
          width="80"
          align="center"
        />
        <el-table-column
          label="上传时间"
          prop="createTime"
          width="160"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:file:manage:download']"
              type="primary"
              size="small"
              link
              @click="handleDownloadFile(scope.row.url, scope.row.name)"
            >
              <template #icon>
                <Download />
              </template>
              下载
            </el-button>
            <el-button
              v-hasPerm="['sys:file:manage:modify']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:file:manage:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 上传弹窗 -->
    <el-dialog
      v-model="addDialog.visible"
      :title="addDialog.title"
      width="500px"
      @close="handleCloseAddDialog"
    >
      <el-form>
        <el-form-item>
          <FileUpload v-model="fileUrls" />
        </el-form-item>
        <el-form-item>
          <span>文件大小不超过20M</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑表单弹窗 -->
    <el-dialog
      v-model="editDialog.visible"
      :title="editDialog.title"
      width="500px"
      @close="handleCloseEditDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-suffix=":"
        label-width="100px"
      >
        <el-form-item label="文件名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入文件名称"
            :maxlength="50"
          />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input
            v-model="formData.remark"
            :rows="4"
            :maxlength="100"
            show-word-limit
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleCloseEditDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "FileManage",
  inheritAttrs: false,
});

import FileAPI, {
  FileManagePageVO,
  FileManageForm,
  FileManagePageQuery,
} from "@/api/file/index";
import { isImageExtension, convertFileSize } from "@/utils/image";
import unknownImg from "@/assets/unknown.png";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<FileManagePageQuery>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
});

// 文件管理表格数据
const pageData = ref<FileManagePageVO[]>([]);

// 文件地址
const fileUrls = ref([]);
const previewList = ref<string[]>([]);

// 弹窗
const addDialog = reactive({
  title: "",
  visible: false,
});
const editDialog = reactive({
  title: "",
  visible: false,
});
// 文件管理表单
const formData = reactive<FileManageForm>({
  id: undefined,
  name: "",
  remark: "",
});

const rules = reactive({
  name: [{ required: true, message: "请输入文件名称", trigger: "blur" }],
});

/** 查询文件管理 */
function handleQuery() {
  loading.value = true;
  FileAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;

      previewList.value.length = 0;
      for (const obj of data.list) {
        if (obj.url?.trim() !== "" && isImageExtension(obj.suffix || "")) {
          previewList.value.push(obj.url + "");
          obj.path = obj.url;
        } else {
          obj.path = unknownImg;
        }
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置文件管理查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 打开文件管理弹窗 */
function handleOpenDialog(id?: number) {
  if (id) {
    editDialog.visible = true;
    editDialog.title = "修改文件";
    FileAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    addDialog.visible = true;
    addDialog.title = "上传文件";
    formData.id = undefined;
  }
}

/** 提交文件管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        FileAPI.modify(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseEditDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭文件管理弹窗 */
function handleCloseAddDialog() {
  addDialog.visible = false;
  fileUrls.value = [];
  handleResetQuery();
}
function handleCloseEditDialog() {
  editDialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id != undefined;
}

/** 删除文件管理 */
function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除该项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      FileAPI.deleteById(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {}
  );
}

/** 下载文件 */
function handleDownloadFile(url: string, fileName: string) {
  FileAPI.downloadFile(url, fileName);
}

function formatterSize(row: FileManagePageVO) {
  return convertFileSize(row.size || 0);
}

onMounted(() => {
  handleQuery();
});
</script>
